package com.frost.blog;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class JWTUtils {

    private final static long EXPIRATION_DATE = 60 * 60 * 1000;

    private final static String secretString = "B6X7jGKKaUqSAPVUF8OxFvVsygtX884/5XMz2oN3Uko=";
    private final static Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));

    // 生成令牌
    @Test
    public void getToken() {
        Map<String, Object> claim = new HashMap<>();
        claim.put("id", 5);
        claim.put("name", "zhangsan");
        String token = Jwts.builder()
                .setClaims(claim) // 设置信息
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_DATE)) // 设置过期时间
                .signWith(key) // 设置签名
                .compact();
        System.out.println(token);
    }

    // 生成key
    @Test
    public void getKey() {
        SecretKey secretKey =  Keys.secretKeyFor(SignatureAlgorithm.HS256);
        String encode = Encoders.BASE64.encode(secretKey.getEncoded()); // 获取签名(key)
        System.out.println(encode);
    }

    // 校验令牌
    @Test
    public void parseToken() {
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiemhhbmdzYW4iLCJpZCI6NX0.aQg2EXcqtwbJlPmmPERW9NU21EbfVljvzwMqCFxOvMU";
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims body = null;
        try {
            body = build.parseClaimsJws(token).getBody();// 解析token
        } catch (Exception e) {
            System.out.println("令牌校验失败");
        }
        System.out.println(body);
    }

}
